import { render } from 'ejs';
import { ThreadBase } from 'lite-ts-thread';
import { TreePSD } from 'psd';

import { ConverterBase } from './base';
import { Node } from './cc';
import { AssertServiceBase, ConverterFactoryBase, FileFactoryBase } from '../../contract';
import { enum_ } from '../../model';

export class CanvasConverter extends ConverterBase {
    public static codeTemplate = `import { _decorator } from 'cc';

import { service } from '../<%= isModal ? '../' : '' %>lite';

const { ccclass, property } = _decorator;

@ccclass('<%= className %>')
export class <%= className %> extends service.CcView<void> {
    protected async onActive() {
    }
}`;

    public constructor(
        private m_Thread: ThreadBase,
        assetService: AssertServiceBase,
        factory: ConverterFactoryBase,
        fileFactory: FileFactoryBase,
        treePSD: TreePSD,
    ) {
        super(assetService, factory, fileFactory, treePSD);
    }

    public async convert() {
        const node = this.createNode({
            x: -this.treePSD.get<number>(enum_.Psd.width) / 2,
            y: this.treePSD.get<number>(enum_.Psd.height) / 2,
        });

        // const filename = this.fileFactory.view.split('/').concat('canvas').join('-');
        // const className = ('-' + filename).replace(/-([a-z])/g, (_, r) => {
        //     return r.toUpperCase();
        // });
        // const canvasFile = this.fileFactory.buildFile('canvas.ts');
        // if (!canvasFile.exists()) {
        //     await canvasFile.write(
        //         render(CanvasConverter.codeTemplate, {
        //             className,
        //             isModal: this.fileFactory.view.includes('/')
        //         }),
        //     );

        //     await this.assetService.refresh(canvasFile.name);
        // }

        // await this.m_Thread.try<void>(async () => {
        //     node.addComponent(className);
        // }, 10, 300);

        await this.addChildren(node);

        //锚点修改
        let nodeDatas: any = await new Promise((s) => {
            const allNode: any[] = [];
            let index = 0;
            node.walk((child: Node) => {
                let depth = -1;
                let childNode = child;
                while (childNode.parent) {
                    childNode = childNode.parent;
                    depth++;
                }

                const worldPos = child.worldPosition;
                const newAnchor = ConverterBase.getCcPropFunc('v2')?.(0.5, 0.5);
                const com = child.getComponent(ConverterBase.getCcPropFunc('UITransform'));
                const oldAnchor = com.anchorPoint;
                //新坐标
                let x = (newAnchor.x - oldAnchor.x) * com.width * child.scale.x;
                let y = (newAnchor.y - oldAnchor.y) * com.height * child.scale.y;
                let newPos = ConverterBase.getCcPropFunc('v3')?.(x + worldPos.x, y + worldPos.y, 0);
                allNode.push({
                    depth: depth,
                    newPos,
                    node: child
                });
                index++;
                if (index == node.walk.length - 1)
                    s(allNode);
            });
        });

        nodeDatas.sort((a: any, b: any) => a.depth - b.depth);
        for (const r of nodeDatas) {
            const element: any = r.node;
            const newAnchor = ConverterBase.getCcPropFunc('v2')?.(0.5, 0.5);

            const com = element.getComponent(ConverterBase.getCcPropFunc('UITransform'));
            element.setWorldPosition(r.newPos);
            com.setAnchorPoint(newAnchor);
        }

        return node;
    }
}